package com.runda.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbjob.mapper.SysRoleFunctionMapper;
import com.bbjob.mapper.SysRoleMapper;
import com.bbjob.model.SysRole;
import com.bbjob.model.SysRoleFunction;
import com.bbjob.util.service.impl.BaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.runda.system.service.RoleService;

import tk.mybatis.mapper.entity.Example;

@Service
public class RoleServiceImpl extends BaseService<SysRole> implements RoleService {

	@Autowired
	private SysRoleMapper rolemapper;
	@Autowired
	private SysRoleFunctionMapper rolemenumapper;

	@Override
	public int saveRole(SysRole role) {
		return rolemapper.insertSelective(role);
	}

	@Override
	public int editRole(SysRole role) {
		return rolemapper.updateByPrimaryKeySelective(role);
	}

	@Override
	public int deleteRole(Integer id) {
		return rolemapper.deleteByPrimaryKey(id);
	}

	@Override
	public PageInfo<SysRole> getlist(SysRole role, int page, int size) {
		PageHelper.startPage(page, size);
		Example example = new Example(SysRole.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtil.isNotEmpty(role.getRoleName())) {
			criteria.andLike("roleName", "%" + role.getRoleName() + "%");
		}
		example.setOrderByClause(" id  desc");
		List<SysRole> resultList = rolemapper.selectByExample(example);
		return new PageInfo<SysRole>(resultList);
	}

	@Override
	public List<SysRole> getAll() {
		Example example = new Example(SysRole.class);
		example.setOrderByClause(" id  desc");
		List<SysRole> resultList = rolemapper.selectByExample(example);
		return resultList;
	}

	@Override
	public int setRoleToMenu(int roleid, String menuid) {
		Example example = new Example(SysRoleFunction.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("roleId", roleid);
		rolemenumapper.deleteByExample(example);
		String[] menu = menuid.split(",");
		for (int i = 0; i < menu.length; i++) {
			SysRoleFunction sys = new SysRoleFunction();
			sys.setRoleId(roleid);
			sys.setFunctionId(Integer.parseInt(menu[i]));
			rolemenumapper.insertSelective(sys);
		}
		return 1;
	}

	@Override
	public List<Integer> getRoleMenu(int roleid) {
		Example example = new Example(SysRoleFunction.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("roleId", roleid);
		List<SysRoleFunction> rolemenu = rolemenumapper.selectByExample(example);
		List<Integer> list = new ArrayList<Integer>();
		for (SysRoleFunction sysRoleFunction : rolemenu) {
			list.add(sysRoleFunction.getFunctionId());
		}
		return list;
	}

}